<?php
 
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 
 include_once PATH."inc/constants.inc.php";
 include_once PATH."common/base.php";
 include_once PATH."inc/class.securrity.php";
 
class autores
{
    private $_db;
    private $_takethemail_db;
	private $security;
    public function __construct($db=NULL)
    {
		$this->security = new security();
        if(is_object($db))
        {
            $this->_db = $db;
        }
        else
        {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
            $this->_db = new PDO($dsn, DB_USER, DB_PASS);
			$this->_db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        }
        
            $dsn = "mysql:host=".TAKETHMAIL_DB_HOST.";dbname=".TAKETHMAIL_DB_NAME;
            $this->_takethemail_db = new PDO($dsn, TAKETHMAIL_DB_USER, TAKETHMAIL_DB_PASS);
            $this->_takethemail_db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }
	
	public function getClientInfo(){	
		$client_info = array ();
		$sql = "SELECT *
                FROM client_info";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()!=0) 
			{
				$row = $stmt->fetch();
				$client_info['client_id'] = $row['client_id'];
				$client_info['client_secret'] = $row['client_secret'];
				$client_info['alias_redirect'] = $row['alias_redirect'];
				$client_info['sub_master_redirect'] = $row['sub_master_redirect'];
			}
		}
		return $client_info;
	}

    public function addfilter($type){
	  $filter = trim($_POST['filter']);
	  if($type == "mail"){
	  
	  	// if(!$this->security->isEmail($filter)
		//){
		//	echo "<label> <font color=\"red\">Invalid MAIL ID, check your input.</font></label>";
		//	return;	
		//}
	  
	  
	      $subject = "ANY";
	      $sql = "INSERT INTO filter(mail_id, subject)
		      VALUES(:filter, :subject)";
	      if($stmt = $this->_db->prepare($sql)){
		  $stmt->bindParam(":filter", $filter, PDO::PARAM_STR);
		  $stmt->bindParam(":subject", $subject, PDO::PARAM_STR);
		  $stmt->execute();
		  $stmt->closeCursor();
		  $smtpID = $this->_db->lastInsertId();
		  $succeed = dechex($smtpID);
		  echo "<label> <font color=\"green\"> Success! MAIL ID FILTER is added.</font></label>";
	      } else {
		  echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
	      }
	  }
	  else {
	      $mail = "ANY";
	      $sql = "INSERT INTO filter(mail_id, subject)
		    VALUES(:mail, :filter)";
	      if($stmt = $this->_db->prepare($sql)){
		  $stmt->bindParam(":filter", $filter, PDO::PARAM_STR);
		  $stmt->bindParam(":mail", $mail, PDO::PARAM_STR);
		  $stmt->execute();
		  $stmt->closeCursor();
		  $smtpID = $this->_db->lastInsertId();
		  $succeed = dechex($smtpID);
		  echo "<label> <font color=\"green\"> Success! SUBJECT FILTER is added.</font></label>";
	      } else {
		  echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
	      }
	  }
    }
    
    
    public function editfilter($type){
	$filter = trim($_POST['filter']);
	  if($type == "mail"){
	      $mail = trim($_GET['mail']);
	      
	      if(!$this->security->isEmail($filter)
		){
			echo "<label> <font color=\"red\">Invalid MAIL ID, check your input.</font></label>";
			return;	
		}
	      
	      
	      
	      $sql = "UPDATE filter SET mail_id=:filter WHERE mail_id=:mail";
	      if($stmt = $this->_db->prepare($sql)){
		  $stmt->bindParam(":filter", $filter, PDO::PARAM_STR);
		  $stmt->bindParam(":mail", $mail, PDO::PARAM_STR);
		  $stmt->execute();
		  $stmt->closeCursor();
		  $smtpID = $this->_db->lastInsertId();
		  $succeed = dechex($smtpID);
		  echo "<label> <font color=\"green\"> Success! MAIL ID FILTER is EDITED.</font></label>";
	      } else {
		  echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
	      }
	  }
	  else {
	      $subject = trim($_GET['subject']);
	      $sql = "UPDATE filter SET subject=:filter WHERE subject=:subject";
	      if($stmt = $this->_db->prepare($sql)){
		  $stmt->bindParam(":filter", $filter, PDO::PARAM_STR);
		  $stmt->bindParam(":subject", $subject, PDO::PARAM_STR);
		  $stmt->execute();
		  $stmt->closeCursor();
		  $smtpID = $this->_db->lastInsertId();
		  $succeed = dechex($smtpID);
		  echo "<label> <font color=\"green\"> Success! SUBJECT FILTER is EDITED.</font></label>";
	      } else {
		  echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
	      }
	  }
    }
    
    public function deletefilter($type){
        $mail = trim($_GET['mail']);
        $sql = "DELETE FROM filter
                WHERE mail_id=:mail";
        if($stmt = $this->_db->prepare($sql)) {
	    $stmt->bindParam(":mail", $mail, PDO::PARAM_STR);
            $stmt->execute();
        }
    }
    
    public function filtermaillist(){
	$sql = "SELECT mail_id
                FROM filter WHERE mail_id!='ANY'";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">NO MAIL ID FILTER added. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">MAIL ID</th>";
					//echo "<th style=\"font-size: 10px; color:white\"></th>";
					//echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<tr>";
    				$row = $stmt->fetch();
						echo "<td>";
							echo $row['mail_id'];
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:filteredit('autores/addnewfilter.php?edit=0&mail=". $row['mail_id'] . "','filteredit','640','480','center','front');\">EDIT</a>";
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:filterdelete('autores/addnewfilter.php?delete=0&mail=". $row['mail_id'] . "','filterdelete','640','480','center','front');\">DELETE</a>";
						echo "</td>";

					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }

    public function filtersubjectlist(){
	$sql = "SELECT subject
                FROM filter WHERE subject!='ANY'";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">NO SUBJECT FILTER added. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">SUBJECT</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<tr>";
    				$row = $stmt->fetch();
						echo "<td>";
							echo $row['subject'];
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:filteredit('autores/addnewfilter.php?edit=0&subject=". $row['subject'] . "','filteredit','640','480','center','front');\">EDIT</a>";
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:filterdelete('autores/addnewfilter.php?delete=0&subject=". $row['subject'] . "','filterdelete','640','480','center','front');\">DELETE</a>";
						echo "</td>";

					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    
    }

	
	public function editsmtp($smtp_id){
        echo $smtp_id;
		$host = trim($_POST['host']);
		$port = trim($_POST['port']);
		$auth = trim($_POST['auth']);
		$secure = trim($_POST['secure']);
		$name = trim($_POST['name']);
		$per_hour = 0; //trim($_POST['per_hour']);
		$per_day = trim($_POST['per_day']);
		
		if($this->security->ifContainsSpace($host)
			 || $this->security->ifContainsSpace($port)
			 || $this->security->ifContainsSpace($auth)
			 || $this->security->ifContainsSpace($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isNumeric($port) || !$this->security->isNumeric($port) || !$this->security->isNumeric($port)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isAlpha($auth)
			 || !$this->security->isAlpha($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

        $sql = "SELECT COUNT(smtp_id) AS theCount
                FROM smtp_info
                WHERE smtp_host=:host
				AND smtp_port=:port
				AND smtp_auth=:auth
				AND smtp_secure=:secure
					WHERE smtp_id=:smtp_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":smtp_id", $smtp_id, PDO::PARAM_INT);
            $stmt->bindParam(":host", $host, PDO::PARAM_STR);
			$stmt->bindParam(":port", $port, PDO::PARAM_INT);
			$stmt->bindParam(":auth", $auth, PDO::PARAM_STR);
			$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
			$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
			{
                echo "<label><font color=\"red\">Error! Sorry, this SMTP is already configured.</font></label>";
            }
			else
			{
				$sql = "UPDATE smtp_info SET smtp_host=:host, smtp_port=:port, smtp_auth=:auth, smtp_secure=:secure, per_hour=:per_hour, per_day=:per_day, name=:name
                WHERE smtp_id=:smtp_id";
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":smtp_id", $smtp_id, PDO::PARAM_INT);
            		$stmt->bindParam(":host", $host, PDO::PARAM_STR);
					$stmt->bindParam(":port", $port, PDO::PARAM_INT);
					$stmt->bindParam(":auth", $auth, PDO::PARAM_STR);
					$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
					$stmt->bindParam(":per_hour", $per_hour, PDO::PARAM_INT);
					$stmt->bindParam(":per_day", $per_day, PDO::PARAM_INT);
					$stmt->bindParam(":name", $name, PDO::PARAM_STR);
        		    $stmt->execute();
		     		$stmt->closeCursor();

           			$smtpID = $this->_db->lastInsertId();
            		$succeed = dechex($smtpID);
            		echo "<label><font color=\"green\">Success! SMTP infomation is added.</font></label>";
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
	}
	
    public function addsmtp()
    {
        $host = trim($_POST['host']);
		$port = trim($_POST['port']);
		$auth = trim($_POST['auth']);
		$secure = trim($_POST['secure']);
		$name = trim($_POST['name']);
		$per_hour = 0; //trim($_POST['per_hour']);
		$per_day = trim($_POST['per_day']);
		
		if($this->security->ifContainsSpace($host)
			 || $this->security->ifContainsSpace($port)
			 || $this->security->ifContainsSpace($auth)
			 || $this->security->ifContainsSpace($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isNumeric($port) || !$this->security->isNumeric($port) || !$this->security->isNumeric($port)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isAlpha($auth)
			 || !$this->security->isAlpha($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

        $sql = "SELECT COUNT(smtp_id) AS theCount
                FROM smtp_info
                WHERE smtp_host=:host
				AND smtp_port=:port
				AND smtp_auth=:auth
				AND smtp_secure=:secure";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":host", $host, PDO::PARAM_STR);
			$stmt->bindParam(":port", $port, PDO::PARAM_INT);
			$stmt->bindParam(":auth", $auth, PDO::PARAM_STR);
			$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this SMTP is already configured.</font></label>";
            }
			else
			{
				$sql = "INSERT INTO smtp_info(smtp_host, smtp_port, smtp_auth, smtp_secure, per_hour, per_day,name)
                VALUES(:host, :port, :auth, :secure, :per_hour, :per_day, :name)";
				if($stmt = $this->_db->prepare($sql))
				{
            		$stmt->bindParam(":host", $host, PDO::PARAM_STR);
					$stmt->bindParam(":port", $port, PDO::PARAM_INT);
					$stmt->bindParam(":auth", $auth, PDO::PARAM_STR);
					$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
					$stmt->bindParam(":per_hour", $per_hour, PDO::PARAM_INT);
					$stmt->bindParam(":per_day", $per_day, PDO::PARAM_INT);
					$stmt->bindParam(":name", $name, PDO::PARAM_STR);
        		    $stmt->execute();
		     		$stmt->closeCursor();

           			$smtpID = $this->_db->lastInsertId();
            		$succeed = dechex($smtpID);
            		echo "<label> <font color=\"green\"> Success! SMTP infomation is added.</font></label>";
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
				
				$sql = "SELECT @row:=0;
						UPDATE smtp_info
						SET smtp_id = (@row:=@row+1)
						ORDER BY smtp_id";
			    if($stmt = $this->_db->prepare($sql))
				{
					$stmt->execute();
		     		$stmt->closeCursor();
				}
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
	
	
	public function smtplist()
	{
        $sql = "SELECT *
                FROM smtp_info";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">SMTP list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">NAME</th>";
					echo "<th style=\"font-size: 10px; color:white\">ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">HOST</th>";
					echo "<th style=\"font-size: 10px; color:white\">PORT</th>";
					echo "<th style=\"font-size: 10px; color:white\">AUTH</th>";
					echo "<th style=\"font-size: 10px; color:white\">SECURE</th>";
					//echo "<th style=\"font-size: 10px; color:white\">Mails/HOUR</th>";
					echo "<th style=\"font-size: 10px; color:white\">Mails/Day</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<tr>";
    				$row = $stmt->fetch();
						echo "<td>";
							echo $row['name'];
						echo "</td>";
						echo "<td>";
							echo $row['smtp_id'];
						echo "</td>";
						echo "<td>";
							echo $row['smtp_host'];
						echo "</td>";
                		echo "<td>";
							echo $row['smtp_port'];
						echo "</td>";
						echo "<td>";
							echo $row['smtp_auth'];
						echo "</td>";
                		echo "<td>";
							echo $row['smtp_secure'];
						echo "</td>";
						//echo "<td>";
						//	echo $row['per_hour'];
						//echo "</td>";
						echo "<td>";
							echo $row['per_day'];
						echo "</td>";
						echo "<td>";
						if($row['smtp_id']>5)
						echo "<a href=\"javascript:smtpedit('autores/addnewsmtp.php?edit=0&smtp=". $row['smtp_id'] . "','smtpedit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";
					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	
	public function smtpselect()
	{
        $sql = "SELECT *
                FROM smtp_info";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                //echo "<label> SMTP list is empty. </label>";
            }
			else
			{
				//<option value="true">TRUE</option>
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<option style=\"background-color:#B2FF99\" value=";
    				$row = $stmt->fetch();
						echo "\"".$row['smtp_id']."\">";
						echo $row['name'];
						/*echo "Host:";
						echo $row['smtp_host'];
						echo " | ";
						echo "Port:";
						echo $row['smtp_port'];
						echo " | ";
						echo "Auth:";
						echo $row['smtp_auth'];
						echo " | ";
                		echo "Secure:";
						echo $row['smtp_secure'];
						*/
						echo "</option>";
				}
			}
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	
	 public function addimap()
    {
        $host = trim($_POST['host']);
		$port = trim($_POST['port']);
		$charset = trim($_POST['charset']);
		$secure = trim($_POST['secure']);
		$name = trim($_POST['name']);
		
		if($this->security->ifContainsSpace($host)
			 || $this->security->ifContainsSpace($port)
			 || $this->security->ifContainsSpace($charset)
			 || $this->security->ifContainsSpace($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isNumeric($port)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isAlpha($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

        $sql = "SELECT COUNT(imap_id) AS theCount
                FROM imap_info
                WHERE imap_host=:host
				AND imap_port=:port
				AND imap_charset=:charset
				AND imap_secure=:secure";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":host", $host, PDO::PARAM_STR);
			$stmt->bindParam(":port", $port, PDO::PARAM_INT);
			$stmt->bindParam(":charset", $charset, PDO::PARAM_STR);
			$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this IMAP is already configured.</font></label>";
            }
			else
			{
				$sql = "INSERT INTO imap_info(imap_host, imap_port, imap_charset, imap_secure, name)
                VALUES(:host, :port, :charset, :secure, :name)";
				if($stmt = $this->_db->prepare($sql))
				{
            		$stmt->bindParam(":host", $host, PDO::PARAM_STR);
					$stmt->bindParam(":port", $port, PDO::PARAM_INT);
					$stmt->bindParam(":charset", $charset, PDO::PARAM_STR);
					$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
					$stmt->bindParam(":name", $name, PDO::PARAM_STR);
        		    $stmt->execute();
		     		$stmt->closeCursor();

           			$imapID = $this->_db->lastInsertId();
            		$succeed = dechex($imapID);
            		echo "<label> <font color=\"green\"> Success! IMAP infomation is added.</font></label>";
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
				
				$sql = "SELECT @row:=0;
						UPDATE imap_info
						SET imap_id = (@row:=@row+1)
						ORDER BY imap_id";
			    if($stmt = $this->_db->prepare($sql))
				{
					$stmt->execute();
		     		$stmt->closeCursor();
				}
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
	
	public function editimap($imap_id)
    {
        $host = trim($_POST['host']);
		$port = trim($_POST['port']);
		$charset = trim($_POST['charset']);
		$secure = trim($_POST['secure']);
		$name = trim($_POST['name']);
		
		if($this->security->ifContainsSpace($host)
			 || $this->security->ifContainsSpace($port)
			 || $this->security->ifContainsSpace($charset)
			 || $this->security->ifContainsSpace($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isNumeric($port)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isAlpha($secure)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

        $sql = "SELECT COUNT(imap_id) AS theCount
                FROM imap_info
                WHERE imap_host=:host
				AND imap_port=:port
				AND imap_charset=:charset
				AND imap_secure=:secure";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":host", $host, PDO::PARAM_STR);
			$stmt->bindParam(":port", $port, PDO::PARAM_INT);
			$stmt->bindParam(":charset", $charset, PDO::PARAM_STR);
			$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this IMAP is already configured.</font></label>";
            }
			else
			{
				$sql = "UPDATE imap_info SET imap_host=:host, imap_port=:port, imap_charset=:charset, imap_secure=:secure, name=:name
                WHERE imap_id=:imap_id";
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":imap_id", $imap_id, PDO::PARAM_INT);
            		$stmt->bindParam(":host", $host, PDO::PARAM_STR);
					$stmt->bindParam(":port", $port, PDO::PARAM_INT);
					$stmt->bindParam(":charset", $charset, PDO::PARAM_STR);
					$stmt->bindParam(":secure", $secure, PDO::PARAM_STR);
					$stmt->bindParam(":name", $name, PDO::PARAM_STR);
        		    $stmt->execute();
		     		$stmt->closeCursor();

           			$imapID = $this->_db->lastInsertId();
            		$succeed = dechex($imapID);
            		echo "<label> <font color=\"green\"> Success! IMAP infomation is added.</font></label>";
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
    
    public function livelist(){
        $sql = "SELECT mailsread, mailssent, mailstotaluni, mailsskipped, mailsfailed, started_on FROM mails where id='total'";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
        }
		$row = $stmt->fetch();
		echo "<table>";
            echo "<tr style=\"background-color:limegreen\">";
                echo "<th style=\"font-size: 10px; color:white\">MAILS READ</th>";
                echo "<th style=\"font-size: 10px; color:white\">MAILS SENT</th>";
                echo "<th style=\"font-size: 10px; color:white\">MAILS POPPED</th>";
                echo "<th style=\"font-size: 10px; color:white\">MAILS SKIPPED<br/>/FILTERED</th>";
                echo "<th style=\"font-size: 10px; color:white\">SENDING FAILED</th>";
                echo "<th style=\"font-size: 10px; color:white\">START TIME</th>";
            echo "</tr>";
            echo "<tr>";
                echo "<td>";
                    echo $row['mailsread'];
				echo "</td>";
				echo "<td>";
                    echo $row['mailssent'];
				echo "</td>";
                echo "<td>";
					echo $row['mailstotaluni'];
				echo "</td>";
				echo "<td>";
					echo $row['mailsskipped'];
				echo "</td>";
				echo "<td>";
					echo $row['mailsfailed'];
				echo "</td>";
                echo "<td>";
                    echo $row['started_on'];
                echo "</td>";
            echo "</tr>";
		echo "</table>";
    }
    
    public function liveCampaignlist(){
        $sql = "SELECT id, mailsread, mailssent, mailstotaluni, mailsskipped, mailsfailed, started_on, notice FROM mails where id LIKE 'campaign%'";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            echo "<table>";
                    echo "<tr style=\"background-color:limegreen\">";
                        echo "<th style=\"font-size: 10px; color:white\">CAMPAIGNS</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS READ</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS SENT</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS POPPED</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS SKIPPED<br/>/FILTERED</th>";
                        echo "<th style=\"font-size: 10px; color:white\">SENDING FAILED</th>";
                        echo "<th style=\"font-size: 10px; color:white\">START TIME</th>";
                        echo "<th style=\"font-size: 10px; color:white\">LIMIT EXCEEDED</th>";
                    echo "</tr>";
                    for($i=0 ; $i<$stmt->rowCount() ; $i++){
                        $row = $stmt->fetch();
                            echo "<tr>";
                                echo "<td>";
                                    echo $row['id'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailsread'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailssent'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailstotaluni'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailsskipped'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailsfailed'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['started_on'];
                                echo "</td>";
                                echo "<td>";
                                    if($row['notice'] == 'NO') echo "<font color=\"limegreen\">" . $row['notice'] . "</font>";
                                    else echo "<font color=\"red\">" . $row['notice'] . "</font>";
                                echo "</td>";
                            echo "</tr>";
                    }
            echo "</table>";
        }
        else
        {
            echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
    
    
    public function liveUserlist(){
        $sql = "SELECT id, campaign_id, mailsread, mailssent, mailstotaluni, mailsskipped, mailsfailed, started_on, notice, poplimit FROM mails, alias_mail where alias_mail.mail_id = mails.id ORDER BY alias_mail.campaign_id ASC";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            echo "<table>";
                    echo "<tr style=\"background-color:limegreen\">";
                        echo "<th style=\"font-size: 10px; color:white\">CAMPAIGN</th>";
                        echo "<th style=\"font-size: 10px; color:white\">SENDER MAIL</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS READ</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS SENT</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS POPPED/LIMIT</th>";
                        echo "<th style=\"font-size: 10px; color:white\">MAILS SKIPPED<br/>/FILTERED</th>";
                        echo "<th style=\"font-size: 10px; color:white\">SENDING FAILED</th>";
                        echo "<th style=\"font-size: 10px; color:white\">START TIME</th>";
                        echo "<th style=\"font-size: 10px; color:white\">LIMIT EXCEEDED FOR NEW POP</th>";
                    echo "</tr>";
                    for($i=0 ; $i<$stmt->rowCount() ; $i++){

                        $row = $stmt->fetch();
                            echo "<tr>";
                                echo "<td>";
                                    echo $row['campaign_id'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['id'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailsread'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailssent'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailstotaluni'] . "/" . $row['poplimit'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailsskipped'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['mailsfailed'];
                                echo "</td>";
                                echo "<td>";
                                    echo $row['started_on'];
                                echo "</td>";
                                echo "<td>";
                                    if($row['notice'] == 'NO') echo "<font color=\"limegreen\">" . $row['notice'] . "</font>";
                                    else echo "<font color=\"red\">" . $row['notice'] . "</font>";
                                echo "</td>";
                            echo "</tr>";
                    }
            echo "</table>";
        }
        else
        {
            echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }

	public function imaplist()
	{
        $sql = "SELECT *
                FROM imap_info";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">IMAP list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">NAME</th>";
					echo "<th style=\"font-size: 10px; color:white\">ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">HOST</th>";
					echo "<th style=\"font-size: 10px; color:white\">PORT</th>";
					echo "<th style=\"font-size: 10px; color:white\">CHARSET</th>";
					echo "<th style=\"font-size: 10px; color:white\">SECURE</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<tr>";
    				$row = $stmt->fetch();
						echo "<td>";
							echo $row['name'];
						echo "</td>";
						echo "<td>";
							echo $row['imap_id'];
						echo "</td>";
						echo "<td>";
							echo $row['imap_host'];
						echo "</td>";
                		echo "<td>";
							echo $row['imap_port'];
						echo "</td>";
						echo "<td>";
							echo $row['imap_charset'];
						echo "</td>";
                		echo "<td>";
							echo $row['imap_secure'];
						echo "</td>";
						echo "<td>";
						if($row['imap_id']>5)
						echo "<a href=\"javascript:imapedit('autores/addnewimap.php?edit=0&imap=". $row['imap_id'] . "','imapedit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";
					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function imapselect()
	{
        $sql = "SELECT *
                FROM imap_info";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                //echo "<label> IMAP list is empty. </label>";
            }
			else
			{
				//<option value="true">TRUE</option>
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<option value=";
    				$row = $stmt->fetch();
						echo "\"".$row['imap_id']."\">";
						echo $row['name'];
						/*echo "Host:";
						echo $row['imap_host'];
						echo " | ";
						echo "Port:";
						echo $row['imap_port'];
						echo " | ";
						echo "Charset:";
						echo $row['imap_charset'];
						echo " | ";
                		echo "Secure:";
						echo $row['imap_secure'];
						*/
						echo "</option>";
				}
			}
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function editsubmaster($mail_id="", $gmail_token=""){
        if($gmail_token!=""){
            $mailid = $mail_id;
            $password = $gmail_token;
        }
        else {
            $name = trim($_POST['name']);
            $mailid = trim($_POST['mailid']);
            $password = trim($_POST['password']);
            $smtp = trim($_POST['smtp']);
            $imap = trim($_POST['imap']);
        }
		
		if($this->security->ifContainsSpace($mailid)
			 || $this->security->ifContainsSpace($password)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(isset($smtp) && isset($imap) && ( !$this->security->isNumeric($smtp)
			|| !$this->security->isNumeric($imap))
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isEmail($mailid)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
        $sql = "SELECT COUNT(mail_id) AS theCount
                FROM sub_master_mail
                WHERE mail_id=:mailid AND :mailid!=:mail_id";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
             $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this POPPING MAIL is already configured.</font></label>";
            }
			else
			{
				
				//check if this sub_master_mail is already in alias and used as a sender in any campaign.
				$sql = "SELECT COUNT(mail_id) AS theCount
						FROM alias_mail
						WHERE mail_id=:mailid AND :mailid!=:mail_id";
				if($stmt = $this->_db->prepare($sql)) {
					$stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
					$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
					$stmt->execute();
					$row = $stmt->fetch();
					if($row['theCount']!=0) 
					{
						echo "<label> <font color=\"red\"> Error! Sorry, this POPPING MAIL is already configured as SENDER MAIL.</font></label>";
						return;
					}
				}
				else
				{
					echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
				}
						
				if($gmail_token == ""){
                    //We are fine to add this mail as a sub_master_mail
                    $sql = "UPDATE sub_master_mail SET name=:name, mail_id=:mailid, password=:password, smtp_id=:smtp, imap_id=:imap, worked=1
                        WHERE mail_id=:mail_id
                    ";
                    if($stmt = $this->_db->prepare($sql))
                    {
                        $stmt->bindParam(":name", $name, PDO::PARAM_STR);
                        $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                        $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
                        $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                        $stmt->bindParam(":smtp", $smtp, PDO::PARAM_INT);
                        $stmt->bindParam(":imap", $imap, PDO::PARAM_INT);
                        $stmt->execute();
                        $stmt->closeCursor();

                        $smtpID = $this->_db->lastInsertId();
                        $succeed = dechex($smtpID);
                        echo "<label> <font color=\"green\"> Success! POPPING MAIL is updated.</font></label>";
                    } else {
                        echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
                    }
                }
        		else {
                    $access_token =  json_decode($password);
                    $refresh_token = $access_token->refresh_token;
                    $sql = "UPDATE sub_master_mail SET password=:password, refresh_token=:refresh_token, worked=1 WHERE mail_id=:mailid";
                    if($stmt = $this->_db->prepare($sql))
                    {
                        $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                        $stmt->bindParam(":refresh_token", $refresh_token, PDO::PARAM_STR);
                        $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                        $stmt->execute();
                        $stmt->closeCursor();
                        echo "<label> <font color=\"green\"> Success! POPPING MAIL Access Token is updated.</font></label>";
                    }
                }
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }	
	}
	
	public function deletesubmaster($mail_id){
				$sql = "UPDATE campaign
						SET is_activated = 0
						WHERE sub_master_mail_id=:mail_id";
			    if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
		
		
				$sql = "DELETE FROM sub_master_mail
					WHERE mail_id=:mail_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "SELECT @row:=0;
						UPDATE campaign
						SET campaign_id = (@row:=@row+1)
						ORDER BY campaign_id";
			    if($stmt = $this->_db->prepare($sql))
				{
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "DELETE FROM mails
                    WHERE id=:mail_id"
                ;
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
	}
	
	public function deletealias($mail_id){
				$sql = "DELETE FROM alias_mail
					WHERE mail_id=:mail_id"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "SELECT @row:=0;
						UPDATE message
						SET message_id = (@row:=@row+1)
						ORDER BY message_id";
			    if($stmt = $this->_db->prepare($sql))
				{
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "DELETE FROM mails
                    WHERE id=:mail_id"
                ;
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
	}
	
	public function verifiedSender($mail_id){
        $sql = "SELECT verified FROM alias_mail
                    WHERE mail_id=:mail_id
                ";
       if($stmt = $this->_db->prepare($sql))
       {
            $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['verified'] >= 2)return true;
            else return false;
        }
        return false;
	}
	
	public function isPossibleAddSubmaster($mailid="",$current_mail_id="")
    {
        $sql = "SELECT COUNT(mail_id) AS theCount
                FROM sub_master_mail
                WHERE mail_id=:mailid";
        if($current_mail_id != "") $sql = $sql ." And mail_id!=:current_mail_id";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
            if($current_mail_id != "") $stmt->bindParam(":current_mail_id", $current_mail_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
            {
                return "<label> <font color=\"red\">Sorry, This POPPING is already Configured.</font></label>";
            }
            else
            {
                //check if this sub_master_mail is already in alias and used as a sender in any campaign.
                $sql = "SELECT COUNT(mail_id) AS theCount
                        FROM alias_mail
                        WHERE mail_id=:mailid";
                if($stmt = $this->_db->prepare($sql)) {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->execute();
                    $row = $stmt->fetch();
                    if($row['theCount']!=0) 
                    {
                        return "<label> <font color=\"red\">Sorry, This POPPING mail is already configured as SENDER mail.</font></label>";
                    }
                }
            }
        }
        return "";
    }
	
	public function addsubmaster()
    {
        $name = trim($_POST['name']);
        $mailid = trim($_POST['mailid']);
        $password = trim($_POST['password']);
        $smtp = trim($_POST['smtp']);
        $imap = trim($_POST['imap']);

        if($this->security->ifContainsSpace($mailid)
			 || $this->security->ifContainsSpace($password)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isNumeric($smtp)
			|| !$this->security->isNumeric($imap)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isEmail($mailid)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		$ret = "";
		$ret = $this->isPossibleAddSubmaster($mailid);
		if( $ret != ""){
            echo $ret;
		}
		else {
            //We are fine to add this mail as a sub_master_mail
                $sql = "INSERT INTO sub_master_mail(name, mail_id, password, smtp_id, imap_id)
                VALUES(:name, :mailid, :password, :smtp, :imap)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":name", $name, PDO::PARAM_STR);
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                    $stmt->bindParam(":smtp", $smtp, PDO::PARAM_INT);
                    $stmt->bindParam(":imap", $imap, PDO::PARAM_INT);
                    $stmt->execute();
                    $stmt->closeCursor();

                    $smtpID = $this->_db->lastInsertId();
                    $succeed = dechex($smtpID);
                    echo "<label> <font color=\"green\"> Success! New POPPING MAIL is added.</font></label>";
                } else {
                    echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
                }
                
                $sql = "INSERT INTO mails(id) 
                        VALUES (:mailid)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
        }
    }

	public function submasterlist()
	{
        $sql = "SELECT *
                FROM sub_master_mail ORDER BY campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">POPPING MAIL list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">NAME</th>";
					echo "<th style=\"font-size: 10px; color:white\">MAIL ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">PASSWORD</th>";
					echo "<th style=\"font-size: 10px; color:white\">SMTP ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">IMAP ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">CAMPAIGN ID</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					$row = $stmt->fetch();
					if($row['worked']==0)echo "<tr style=\"background-color:#FFCCCC\">";
					//else if($row['worked']==1)echo "<tr style=\"background-color:#CCFFCC\">";
					else echo "<tr>";
						echo "<td>";
							echo $row['name'];
						echo "</td>";
                		echo "<td>";
							echo $row['mail_id'];
						echo "</td>";
						echo "<td>";
                            if(strstr($row['password'],"access_token")) echo "Token is Set";
                            else if(strstr($row['mail_id'],"@gmail.com") != false) echo "<font color=\"red\">INVALID, Please edit and Login Again</font>";
							else 
                                //echo $row['password'];
                                echo "Password is Set";
						echo "</td>";
                		echo "<td>";
							echo $row['smtp_id'];
						echo "</td>";
							echo "<td>";
							echo $row['imap_id'];
						echo "</td>";
						echo "<td>";
							if($row['campaign_id'] != 0)echo $row['campaign_id'];
							else echo "Not Added";
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:submasteredit('autores/addnewsubmaster.php?edit=0&submaster=". $row['mail_id'] . "','submasteredit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:submasterdelete('autores/addnewsubmaster.php?delete=0&submaster=". $row['mail_id'] . "','submasterdelete','640','480','center','front');\">
        DELETE</a>";
						echo "</td>";
    
					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function smtpUser($user_id){
        $sql = "SELECT Username
                FROM users
                WHERE Username=:user_id AND smtp=1 LIMIT 1";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":user_id", $user_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if(isset($row['Username']))return true;
        }
        return false;
    }
    
	public function tokenlist()
	{
                echo "<table>";
                echo "<tr style=\"background-color:limegreen\">";
                    echo "<th style=\"font-size: 10px; color:white\">Description</th>";
                    echo "<th style=\"font-size: 10px; color:white\">Token</th>";
                echo "</tr>";
                
                echo "<tr>";
                        echo "<td>";
                            echo "Customer Full Name";
                        echo "</td>";
                        echo "<td>";
                            echo "{name}";
                        echo "</td>";
                echo "</tr>";
                echo "<tr>";
                        echo "<td>";
                            echo "Customer First Name";
                        echo "</td>";
                        echo "<td>";
                            echo "{fname}";
                        echo "</td>";
                echo "</tr>";
                    /*echo "<tr>";
                        echo "<td>";
                            echo "Current Day";
                        echo "</td>";
                        echo "<td>";
                            echo "{day}";
                        echo "</td>";
                    echo "</tr>";
                    echo "<tr>";
                        echo "<td>";
                            echo "Current Time";
                        echo "</td>";
                        echo "<td>";
                            echo "{day}";
                        echo "</td>";
                    echo "</tr>";
                    */
                echo "</table>";

	}
	
	public function delayMailSchedule()
    {
        $sql = "SELECT A.sender, A.campaign_id, A.message_id, A.fire, A.from_mail FROM send_delay_mail as A WHERE isFired = 0 AND A.message_id <= (select MAX(delay_message_id) from delay_message as B WHERE A.campaign_id = B.campaign_id) AND A.fire != STR_TO_DATE('2020-01-01 00:00:01','%Y-%m-%d %H:%i:%s')
                ORDER BY fire";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
            {
                echo "<label> <font color=\"red\"> No mails to send.</font></label>";
            }
            else
            {
                echo "<table>";
                echo "<tr style=\"background-color:limegreen\">";
                    echo "<th style=\"font-size: 10px; color:white\">SENDER</th>";
                    echo "<th style=\"font-size: 10px; color:white\">TO</th>";
                    echo "<th style=\"font-size: 10px; color:white\">CAMPAIGN</th>";
                    echo "<th style=\"font-size: 10px; color:white\">FOLLOW-UP MESSAGE</th>";
                    echo "<th style=\"font-size: 10px; color:white\">SENDING TIME</th>";
                echo "</tr>";
                for($i=0 ; $i<$stmt->rowCount() ; $i++){
                    $row = $stmt->fetch();
                    echo "<tr>";
                        echo "<td>";
                            echo $row['sender'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['from_mail'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['campaign_id'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['message_id'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['fire'];
                        echo "</td>";    
                    echo "</tr>";
                }
                echo "</table>";
            }
        }
        else
        {
            echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
	
	
	public function mailSchedule()
    {
        $sql = "SELECT A.sender, A.campaign_id, A.message_id, A.fire, A.from_mail FROM send_mail as A WHERE isFired = 0 AND A.message_id <= (select MAX(message_id) from message as B WHERE A.campaign_id = B.campaign_id) AND A.fire != STR_TO_DATE('2020-01-01 00:00:01','%Y-%m-%d %H:%i:%s')
                ORDER BY fire";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
            {
                echo "<label> <font color=\"red\"> No mails to send.</font></label>";
            }
            else
            {
                echo "<table>";
                echo "<tr style=\"background-color:limegreen\">";
                    echo "<th style=\"font-size: 10px; color:white\">SENDER</th>";
                    echo "<th style=\"font-size: 10px; color:white\">TO</th>";
                    echo "<th style=\"font-size: 10px; color:white\">CAMPAIGN</th>";
                    echo "<th style=\"font-size: 10px; color:white\">MESSAGE</th>";
                    echo "<th style=\"font-size: 10px; color:white\">SENDING TIME</th>";
                echo "</tr>";
                for($i=0 ; $i<$stmt->rowCount() ; $i++){
                    $row = $stmt->fetch();
                    echo "<tr>";
                        echo "<td>";
                            echo $row['sender'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['from_mail'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['campaign_id'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['message_id'];
                        echo "</td>";
                        echo "<td>";
                            echo $row['fire'];
                        echo "</td>";    
                    echo "</tr>";
                }
                echo "</table>";
            }
        }
        else
        {
            echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
	
	public function aliaslist($campaign_id)
	{
        $sql = "SELECT *
                FROM alias_mail WHERE campaign_id=:campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">SENDER list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">NAME</th>";
					echo "<th style=\"font-size: 10px; color:white\">MAIL ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">PASSWORD</th>";
					echo "<th style=\"font-size: 10px; color:white\">SMTP</th>";
					echo "<th style=\"font-size: 10px; color:white\">IMAP</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					$row = $stmt->fetch();
					if($row['worked']==0)echo "<tr style=\"background-color:#FFCCCC\">";
					//else if($row['worked']==1)echo "<tr style=\"background-color:#CCFFCC\">";
					else echo "<tr>";
						echo "<td>";
							echo $row['name'];
						echo "</td>";
                		echo "<td>";
							echo $row['mail_id'];
						echo "</td>";
						echo "<td>";
						if(strstr($row['password'],"access_token")) echo "Token is Set";
						else if(strstr($row['mail_id'],"@gmail.com") != false) echo "<font color=\"red\">INVALID, Please edit and Login Again</font>";
                        else 
							//echo $row['password'];
							echo "Password is Set";
						echo "</td>";
                		echo "<td>";
							echo $row['smtp_id'];
						echo "</td>";
						echo "<td>";
							echo $row['imap_id'];
						echo "</td>";
						echo "<td>";
						if($row['imap_id']!=5)
						echo "<a href=\"javascript:aliasedit('addnewalias.php?edit=0&alias=".$row['mail_id']."&campaign=". $row['campaign_id']."','aliasedit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";
						echo "<td>";
						if($row['imap_id']!=5)
						echo "<a href=\"javascript:aliasdelete('addnewalias.php?delete=0&alias=". $row['mail_id']."&campaign=". $row['campaign_id']."','aliasdelete','640','480','center','front');\">
        DELETE</a>";
						echo "</td>";
    
					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
	}
	
	public function isValidUser($user_id){
        $sql = "SELECT Username
                FROM users
                WHERE Username=:user_id LIMIT 1";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":user_id", $user_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if(isset($row['Username']))return true;
        }
        return false;
	}
	
	public function isPossibleAddAlias($campaign_id, $mailid="", $current_mail_id="")
    {
        $sql = "SELECT COUNT(mail_id) AS theCount
                FROM alias_mail
                WHERE mail_id=:mailid";
        
        if($current_mail_id != "") $sql = $sql ." And mail_id!=:current_mail_id";
        
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
            if($current_mail_id != "") $stmt->bindParam(":current_mail_id", $current_mail_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
            {
                return "<label> <font color=\"red\"> Error! Sorry, this SENDER MAIL is already configured.</font></label>";
                
            }
            else
            {
                $sql = "SELECT COUNT(mail_id) AS theCount
                    FROM sub_master_mail
                    WHERE mail_id=:mailid";
                if($stmt = $this->_db->prepare($sql)) {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->execute();
                    $row = $stmt->fetch();
                    if($row['theCount'] == 0) 
                    {
                        return "";
                    }
                }
                $sql = "SELECT COUNT(mail_id) AS theCount
                    FROM sub_master_mail
                    WHERE mail_id=:mailid AND campaign_id =:campaign_id
                     ;";
                if($stmt = $this->_db->prepare($sql)) {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                    $stmt->execute();
                    $row = $stmt->fetch();
                    if($row['theCount'] == 1) 
                    {
                        return "";
                    }
                    else {
                        return "<label> <font color=\"red\"> Error! Sorry, this SENDER MAIL is already configured As POPPING MAIL.</font></label>";
                    }
                }
            }
        }
        return "";
    }
    
    public function deletegenalias($campaign_id){
        $sql = "SELECT mail_id
                    FROM alias_mail
                    WHERE mail_id LIKE '%takethemail.com' AND campaign_id =:campaign_id;";
                if($stmt = $this->_db->prepare($sql)) {
                    $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                    $stmt->execute();
                    for($i=0 ; $i<$stmt->rowCount() ; $i++){
                        $row = $stmt->fetch();
                        $mailid = $row['mail_id'];
                        
                        $ssql = "DELETE FROM virtual_users WHERE email=:mailid";
                        if($sstmt = $this->_takethemail_db->prepare($ssql))
                        {
                            $sstmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                            $sstmt->execute();
                            $sstmt->closeCursor();
                        }
                    }
                }
    }
    
    public function isexisttakethemail($campaign_id){
        $sql = "SELECT mail_id
                    FROM alias_mail
                    WHERE mail_id LIKE '%takethemail.com' AND campaign_id =:campaign_id;";
                if($stmt = $this->_db->prepare($sql)) {
                    $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                    $stmt->execute();
                    $row = $stmt->fetch();
                    if(isset($row['mail_id'])) return true;
                    else return false;
                }
        return false;
    }

    public function genalias($campaign_id, $name)
    { //_takethemail_db
        
        $suffix = rand(100,999);
        $prefix = str_replace(' ','',$name);
                
        for($i=1;$i<=15;$i++){
                $mailid = $prefix.$suffix.$i."@takethemail.com";
                $password = $prefix.$suffix.$i."1";
                
                $sql = "INSERT INTO virtual_users (domain_id, password , email) 
                VALUES ('1', ENCRYPT(:password, CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), :mailid)";
                if($stmt = $this->_takethemail_db->prepare($sql))
                {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();

                    $smtpID = $this->_db->lastInsertId();
                    $succeed = dechex($smtpID);
                    //echo "<label> <font color=\"green\"> Success! New SENDER MAIL is added.</font></label>";
                } else {
                    //echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
                }
                
                $smtp = 5;
                $imap = 5;
                $sql = "INSERT INTO alias_mail(name, mail_id, password, smtp_id, imap_id, campaign_id)
                VALUES(:name, :mailid, :password, :smtp, :imap, :campaign_id)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":name", $name, PDO::PARAM_STR);
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                    $stmt->bindParam(":smtp", $smtp, PDO::PARAM_INT);
                    $stmt->bindParam(":imap", $imap, PDO::PARAM_INT);
                    $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                    $stmt->execute();
                    $stmt->closeCursor();

                    $smtpID = $this->_db->lastInsertId();
                    $succeed = dechex($smtpID);
                    //echo "<label> <font color=\"green\"> Success! New SENDER MAIL is added.</font></label>";
                } else {
                    //echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
                }
                
                $sql = "INSERT INTO mails(id) 
                        VALUES (:mailid)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
                echo "<label> <font color=\"green\"> Success! New SENDER MAIL is added.</font></label>";
        }

    }
	
	public function addalias($campaign_id)
    {
        $name = trim($_POST['name']);
        $mailid = trim($_POST['mailid']);
        $password = trim($_POST['password']);
        $smtp = trim($_POST['smtp']);
        $imap = trim($_POST['imap']);

		if($campaign_id < 1){
			echo "<label> <font color=\"red\">Invalid Data, CAMPAIGN NOT SET.</font></label>";
			return;
		}
		
		if($this->security->ifContainsSpace($mailid)
			 || $this->security->ifContainsSpace($password)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isNumeric($smtp)
			|| !$this->security->isNumeric($imap)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isEmail($mailid)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		$ret = "";
        $ret = $this->isPossibleAddAlias($campaign_id, $mailid);
        if($ret != ""){
            echo $ret;
        }
        else {
                //echo "name:" . $name . "<br/>";
                //echo "mail_id:" . $mailid . "<br/>";
                //echo "password:" . $password . "<br/>";
                //echo "smtp_id:" . $smtp . "<br/>";
                //echo "imap_id:" . $imap . "<br/>";
                //echo "campaign_id:" . $campaign_id . "<br/>";

                $sql = "INSERT INTO alias_mail(name, mail_id, password, smtp_id, imap_id, campaign_id)
                VALUES(:name, :mailid, :password, :smtp, :imap, :campaign_id)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":name", $name, PDO::PARAM_STR);
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                    $stmt->bindParam(":smtp", $smtp, PDO::PARAM_INT);
                    $stmt->bindParam(":imap", $imap, PDO::PARAM_INT);
                    $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                    $stmt->execute();
                    $stmt->closeCursor();

                    $smtpID = $this->_db->lastInsertId();
                    $succeed = dechex($smtpID);
                    echo "<label> <font color=\"green\"> Success! New SENDER MAIL is added.</font></label>";
                } else {
                    echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
                }
                
                $sql = "INSERT INTO mails(id) 
                        VALUES (:mailid)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
        }
    }
    
    public function deleteNotVerifiedAlias(){
        $sql = "SELECT * FROM alias_mail WHERE mail_id LIKE '%gmail.com' AND (password NOT LIKE '%access_token%' OR verified < 2)";
        
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0)
            {
                //echo "<label> IMAP list is empty. </label>";
            }
            else
            {
                //<option value="true">TRUE</option>
                for($i=0 ; $i<$stmt->rowCount() ; $i++){
                    $row = $stmt->fetch();
                        $this->deletealias($row['mail_id']);
                }
                echo "alias mail deleted";
            }
        }
        else
        {
            //echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
    }
	
	public function editalias($mail_id="", $gmail_token="")
	{
        if($gmail_token!=""){
            $mailid = $mail_id;
            $password = $gmail_token;
        }
        else {
            $name = trim($_POST['name']);
            $mailid = trim($_POST['mailid']);
            $password = trim($_POST['password']);
            $smtp = trim($_POST['smtp']);
            $imap = trim($_POST['imap']);
        }
		
		if($this->security->ifContainsSpace($mailid)
			 || $this->security->ifContainsSpace($password)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(isset($smtp) && isset($imap) && (!$this->security->isNumeric($smtp)
			|| !$this->security->isNumeric($imap))
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isEmail($mailid)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

        $sql = "SELECT COUNT(mail_id) AS theCount
                FROM alias_mail
                WHERE mail_id=:mailid AND :mailid!=:mail_id";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
            $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this SENDER MAIL is already configured.</font></label>";
            }
			else
			{
				$sql = "SELECT COUNT(mail_id) AS theCount
                	FROM sub_master_mail
                	WHERE mail_id=:mailid AND :mailid!=:mail_id";
				if($stmt = $this->_db->prepare($sql)) {
					$stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
					$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
					$stmt->execute();
					$row = $stmt->fetch();
					if($row['theCount']!=0) 
					{
						echo "<label> <font color=\"red\"> Error! Sorry, this SENDER MAIL is already configured As POPPING MAIL.</font></label>";
						return;
					}
				}
				
				if($gmail_token == ""){
                    $sql = "UPDATE alias_mail SET name=:name, mail_id=:mailid, password=:password, smtp_id=:smtp, imap_id=:imap, worked=1
                        WHERE mail_id=:mail_id";
                    if($stmt = $this->_db->prepare($sql))
                    {
                        $stmt->bindParam(":name", $name, PDO::PARAM_STR);
                        $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                        $stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
                        $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                        $stmt->bindParam(":smtp", $smtp, PDO::PARAM_INT);
                        $stmt->bindParam(":imap", $imap, PDO::PARAM_INT);
                        $stmt->execute();
                        $stmt->closeCursor();

                        $aliasID = $this->_db->lastInsertId();
                        $succeed = dechex($aliasID);
                        echo "<label> <font color=\"green\"> Success! SENDER MAIL is Updated.</font></label>";
                    } else {
                        echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
                    }
                }
        		else{
                    $access_token =  json_decode($password);
                    $refresh_token = $access_token->refresh_token;
                    $sql = "UPDATE alias_mail SET password=:password, refresh_token=:refresh_token, verified=verified+1, worked=1 WHERE mail_id=:mailid";
                    if($stmt = $this->_db->prepare($sql))
                    {
                        $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
                        $stmt->bindParam(":password", $password, PDO::PARAM_STR);
                        $stmt->bindParam(":refresh_token", $refresh_token, PDO::PARAM_STR);
                        $stmt->execute();
                        $stmt->closeCursor();
                        echo "<label> <font color=\"green\"> Success! SENDER MAIL Access Token is updated.</font></label>";
                    }
                }
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
	}
	
	
	public function sub_master_mail_id_select($edit, $campaign_id)
	{
		$thisSubMaster = "";
		if(isset($edit) && isset($campaign_id)){
				$thisSubMaster = " OR campaign_id =".$campaign_id;
		}
        $sql = "SELECT *
                FROM sub_master_mail WHERE campaign_id = 0" . $thisSubMaster;
				
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                //echo "<label> IMAP list is empty. </label>";
            }
			else
			{
				//<option value="true">TRUE</option>
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<option value=";
    				$row = $stmt->fetch();
						echo "\"".$row['mail_id']."\">";
						echo $row['mail_id'];
						echo "</option>";
				}
			}
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function editcampaign()
	{
		$name = trim($_POST['name']);
        $mailid = trim($_POST['sub_master_mail_id']);
		$campaign_id = trim($_GET['campaign']);
		
		if(!$this->security->isNumeric($campaign_id)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isEmail($mailid)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
        $sql = "SELECT COUNT(sub_master_mail_id) AS theCount
                FROM campaign
                WHERE sub_master_mail_id=:mailid AND campaing_id!=:campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
            $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this POPPING MAIL is already in use in another CAMPAIGN.</font></label>";
            }
			else
			{
				$sql = "UPDATE campaign SET campaign_name=:name, sub_master_mail_id=:mailid
				WHERE campaign_id=:campaign_id";
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_STR);
            		$stmt->bindParam(":name", $name, PDO::PARAM_STR);
					$stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
        		    $stmt->execute();
		     		$stmt->closeCursor();
					
        		}
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
        $sql = "UPDATE sub_master_mail SET campaign_id=:campaign_id
				WHERE mail_id=:mailid";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_INT);
            $stmt->execute();
		}
		else
		{
        	echo "<label><font color=\"red\">Error Updating POPPING MAIL</font></label>";
        }
        
        
        
	}
	
	public function deletecampaign($campaign){
		$campaign_id = trim($_GET['campaign']);
		
        $this->deletegenalias($campaign_id);

				$sql = "DELETE FROM campaign
					WHERE campaign_id=:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "UPDATE campaign
					SET campaign_id=campaign_id-1 WHERE campaign_id>:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				$sql = "UPDATE sub_master_mail
					SET campaign_id=0 WHERE campaign_id=:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				$sql = "UPDATE sub_master_mail
					SET campaign_id=campaign_id-1 WHERE campaign_id>:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$id = 'campaign'.$campaign_id;
				$sql = "DELETE FROM mails
                    WHERE id=:id OR id IN (select mail_id from alias_mail where campaign_id=:id)"
                ;
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":id", $id, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
	}
	
	public function addcampaign()
    {
		$name = trim($_POST['name']);
        $mailid = trim($_POST['sub_master_mail_id']);
		$campaign_id = $this->totalCampaign() + 1;
		
		if($campaign_id > 3) {
            echo "<label> <font color=\"red\">Campaign Limit Exceeded!!</font></label>";
            return; 		
		}
		
		if(!$this->security->isNumeric($campaign_id)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
		if(!$this->security->isEmail($mailid)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
        $sql = "SELECT COUNT(sub_master_mail_id) AS theCount
                FROM campaign
                WHERE sub_master_mail_id=:mailid";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
            $stmt->execute();
            $row = $stmt->fetch();
            if($row['theCount']!=0) 
			{
                echo "<label> <font color=\"red\"> Error! Sorry, this POPPING MAIL is already in use in another CAMPAIGN.</font></label>";
            }
			else
			{
				$sql = "INSERT INTO campaign(campaign_id, campaign_name, sub_master_mail_id)
                VALUES(:campaign_id, :name, :mailid)";
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_STR);
            		$stmt->bindParam(":name", $name, PDO::PARAM_STR);
					$stmt->bindParam(":mailid", $mailid, PDO::PARAM_STR);
        		    $stmt->execute();
		     		$stmt->closeCursor();
					
           			$campaignID = $this->_db->lastInsertId();
            		$succeed = dechex($campaignID);
					if(isset($succeed)){
            			echo "<label> <font color=\"green\"> Success! New CAMPAIGN is added.</font></label>";
					}
					else{
						echo "<label> <font color=\"red\">Failed! Campaign not added.</font></label>";
					}
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
        		
        		$id = "campaign".$campaign_id;
        		$sql = "INSERT INTO mails(id) 
                        VALUES (:id)";
                if($stmt = $this->_db->prepare($sql))
                {
                    $stmt->bindParam(":id", $id, PDO::PARAM_STR);
                    $stmt->execute();
                    $stmt->closeCursor();
                }
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
		
		$sql = "UPDATE sub_master_mail SET campaign_id=:campaign_id
				WHERE mail_id=:mailid";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->bindParam(":mailid", $mailid, PDO::PARAM_INT);
            $stmt->execute();
		}
		else
		{
        	echo "<label><font color=\"red\">Error Updating POPPING MAIL</font></label>";
        }
    }
	
	
	public function campaignlist()
	{
        $sql = "SELECT *
                FROM campaign";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">CAMPAIGN list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
                    echo "<th style=\"font-size: 10px; color:white\">CAMPAIGN ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">CAMPAIGN NAME</th>";
					echo "<th style=\"font-size: 10px; color:white\">POPPING MAIL</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\">CHANGE STATE</th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					$row = $stmt->fetch();
					if($row['is_activated']==0)echo "<tr style=\"background-color:#CCE5FF\">";
					else if($row['is_activated']==1)echo "<tr style=\"background-color:#CCFFCC\">";
					else echo "<tr>";
					    echo "<td>";
                            echo $row['campaign_id'];
                        echo "</td>";
						echo "<td>";
							echo $row['campaign_name'];
						echo "</td>";
                		echo "<td>";
							if(isset($row['sub_master_mail_id']) && $row['sub_master_mail_id'] !="")echo $row['sub_master_mail_id'];
							else echo "<font color=\"red\">No Master Mail, Campaign not Active.</font>";
						echo "</td>";
						echo "<td>";
							echo "<a href=\"javascript:messageadd('autores/message.php?campaign=". $row['campaign_id'] . "','messageadd','1000','700','center','front');\">
        VIEW</a>";
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:campaignedit('autores/addnewcampaign.php?edit=0&campaign=". $row['campaign_id'] . "','campaignedit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";
						echo "<td>";
						echo "<a href=\"javascript:campaigndelete('autores/addnewcampaign.php?delete=0&campaign=". $row['campaign_id'] . "','campaigndelete','640','480','center','front');\">
        DELETE</a>";
						echo "</td>";
						echo "<td>";
						if($row['is_activated'] == 1)
							echo "<a href=\"javascript:campaignactivate('autores/addnewcampaign.php?activate=10&campaign=". $row['campaign_id'] . "','campaignactivate','640','480','center','front');\">
        <font color=\"green\">Deactivate</font></a>";
						else 
							echo "<a href=\"javascript:campaignactivate('autores/addnewcampaign.php?activate=11&campaign=". $row['campaign_id'] . "','campaignactivate','640','480','center','front');\">
        <font color=\"blue\">Activate</font></a>";
						echo "</td>";
					//echo "<br\>";
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function campaignactivate($campaign_id, $is_activated){
		
		$sql = "UPDATE campaign set is_activated=:is_activated WHERE campaign_id=:campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
			$stmt->bindParam(":is_activated", $is_activated, PDO::PARAM_INT);
            $stmt->execute();
		}
	}
	
	public function alias_mail_id_select($campaign_id)
	{
        $sql = "SELECT *
                FROM alias_mail 
				WHERE 
					alias_mail.mail_id NOT IN 
					(
						SELECT mail_id from sub_master_mail
							WHERE mail_id NOT IN 
							(
								select sub_master_mail_id FROM campaign 
									WHERE campaign_id = :campaign_id
							)
					)
				AND
					alias_mail.mail_id NOT IN
					(
						SELECT alias_mail_id from message
							WHERE campaign_id != :campaign_id
					)
				"
				;
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                //echo "<label> <font color=\"red\">IMAP list is empty. </font></label>";
            }
			else
			{
				//<option value="true">TRUE</option>
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<option value=";
    				$row = $stmt->fetch();
						echo "\"".$row['mail_id']."\">";
						echo $row['mail_id'];
						echo "</option>";
				}
			}
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function totalCampaign(){
			$sql = "SELECT count(campaign_id) as theCount FROM campaign";
        if($stmt = $this->_db->prepare($sql)) {
            $stmt->execute();
			$row = $stmt->fetch();
			return $row['theCount'];
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		return 0;
	}
	
	public function totalMessage($campaign_id){
			$sql = "SELECT count(message_id) as theCount FROM message WHERE campaign_id=:campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
			$row = $stmt->fetch();
			return $row['theCount'];
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		return 0;
	}
	
	public function totalDealyMessage($campaign_id, $message_id){
			$sql = "SELECT count(delay_message_id) as theCount FROM delay_message where campaign_id=:campaign_id
			AND message_id=:message_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
			$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
            $stmt->execute();
			$row = $stmt->fetch();
			return $row['theCount'];
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		return 0;
	}
	
	public function editmessage(){
		$campaign_id = trim($_GET['campaign']);
		$edit = trim($_GET['edit']);
		$message_id = trim($_GET['message']);
		$ishtml = trim($_POST['ishtml']);
		$delay = trim($_POST['delay']);
        $message = trim($_POST['message']);
        $FILES = $_FILES;
        
        $message = $this->makeClickableLinks($message);
        //$message = nl2br($message);
		
		if(!$this->security->isNumeric($campaign_id)
			|| !$this->security->isNumeric($message_id)
			|| !$this->security->isNumeric($delay)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		

				$sql = "UPDATE message SET message=:message, isHTML=:ishtml, delay=:delay
					WHERE message_id=:message_id AND campaign_id=:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
					$stmt->bindParam(":message", $message, PDO::PARAM_STR);
					$stmt->bindParam(":ishtml", $ishtml, PDO::PARAM_INT);
					$stmt->bindParam(":delay", $delay, PDO::PARAM_INT);
        		    $stmt->execute();
		     		$stmt->closeCursor();
					
           			$messageID = $this->_db->lastInsertId();
            		$succeed = dechex($messageID);
					if(isset($succeed)){
            			echo "<label> <font color=\"green\"> Success! MESSAGE is edited successfully.</font></label>";
					}
					else{
						echo "<label> <font color=\"red\">Failed! MESSAGE not edited.</font></label>";
					}
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
				$this->deleteMessageAttachment($campaign_id,$message_id);
				$this->addmessageattachment($campaign_id,$message_id,$FILES);
	}
	
	public function deleteMessageAttachment($campaign_id,$message_id){
		$sql = "DELETE FROM message_attachment where campaign_id=:campaign_id
			AND message_id=:message_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
			$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
            $stmt->execute();
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }	
	}
	
	public function deleteDelayMessageAttachment($campaign_id,$delay_message_id){
		$sql = "DELETE FROM delay_message_attachment where campaign_id=:campaign_id
			AND delay_message_id=:delay_message_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
			$stmt->bindParam(":delay_message_id", $delay_message_id, PDO::PARAM_INT);
            $stmt->execute();
		}
		else
		{
        	//echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }	
	}
	
	public function adddelaymessage()
        {
		$campaign_id = trim($_GET['campaign']);
		$message_id = 1;
		$ishtml = trim($_POST['ishtml']);
		$delay = trim($_POST['delay']);
        $delay_message = trim($_POST['delaymessage']);
		$delay_message_id = $this->totalDealyMessage($campaign_id, $message_id) + 1;

		$delay_message = $this->makeClickableLinks($delay_message);
        //$delay_message = nl2br($delay_message);
		
		$FILES = $_FILES;
		
		if(!$this->security->isNumeric($campaign_id)
			|| !$this->security->isNumeric($message_id)
			|| !$this->security->isNumeric($delay_message_id)
			|| !$this->security->isNumeric($delay)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

				$sql = "INSERT INTO delay_message(delay_message_id, campaign_id, message_id, delay_message, isHTML, delay)
                VALUES(:delay_message_id,:campaign_id, :message_id, :delay_message, :ishtml, :delay)";
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":delay_message_id", $delay_message_id, PDO::PARAM_INT);
            		$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
					$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
					$stmt->bindParam(":delay_message", $delay_message, PDO::PARAM_STR);
					$stmt->bindParam(":ishtml", $ishtml, PDO::PARAM_INT);
					$stmt->bindParam(":delay", $delay, PDO::PARAM_INT);
        		    $stmt->execute();
		     		$stmt->closeCursor();
					
           			$messageID = $this->_db->lastInsertId();
            		$succeed = dechex($messageID);
					if(isset($succeed)){
            			echo "<label> <font color=\"green\">Success! New FOLLOW UP MESSAGE is added.</font></label>";
					}
					else{
						echo "<label> <font color=\"red\">Failed! FOLLOW UP MESSAGE not added.</font></label>";
					}
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
				
				$this->adddelaymessageattachment($campaign_id,$delay_message_id,$FILES);
    }
	
	public function editdelaymessage(){
		$campaign_id = trim($_GET['campaign']);
		$edit = trim($_GET['edit']);
		$message_id = trim($_GET['message']);
		$delaymessage_id = trim($_GET['delaymessage']);
		$ishtml = trim($_POST['ishtml']);
		$delay = trim($_POST['delay']);
        $delaymessage = trim($_POST['delaymessage']);

		$delaymessage = $this->makeClickableLinks($delaymessage);
        //        $delaymessage = nl2br($delaymessage);
		
		$FILES = $_FILES;
				
		if(!$this->security->isNumeric($campaign_id)
			|| !$this->security->isNumeric($message_id)
			|| !$this->security->isNumeric($delaymessage_id)
			|| !$this->security->isNumeric($delay)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}

				$sql = "UPDATE delay_message SET delay_message=:delaymessage, isHTML=:ishtml, delay=:delay
					WHERE message_id=:message_id AND campaign_id=:campaign_id AND delay_message_id=:delaymessage_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
					$stmt->bindParam(":delaymessage", $delaymessage, PDO::PARAM_STR);
					$stmt->bindParam(":ishtml", $ishtml, PDO::PARAM_INT);
					$stmt->bindParam(":delay", $delay, PDO::PARAM_INT);
					$stmt->bindParam(":delaymessage_id", $delaymessage_id, PDO::PARAM_INT);
        		    $stmt->execute();
		     		$stmt->closeCursor();
					
           			$messageID = $this->_db->lastInsertId();
            		$succeed = dechex($messageID);
					if(isset($succeed)){
            			echo "<label> <font color=\"green\"> Success! FOLLOW UP MESSAGE is edited successfully.</font></label>";
					}
					else{
						echo "<label> <font color=\"red\">Failed! FOLLOW UP MESSAGE not edited.</font></label>";
					}
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
				
				$this->deleteDelayMessageAttachment($campaign_id,$delaymessage_id);
				$this->adddelaymessageattachment($campaign_id,$delaymessage_id,$FILES);
	}
	
	public function addmessageattachment($campaign_id, $message_id, $FILES){
                $files = array ('file1','file2','file3');
                foreach($files as $file){
		    //str_replace($FILES[$file]["name"],' ', $mail->to)
                    if(!isset($FILES[$file]) || $FILES[$file]["name"] == "") continue;
                    
                    $target_dir = $_SERVER["DOCUMENT_ROOT"] . '/bytefact/images/';
                    $path = $target_dir . time() ."_". $FILES[$file]["name"];
                    $sql = "INSERT INTO message_attachment(campaign_id, message_id, path)
                            VALUES(:campaign_id, :message_id, :path)";
                    if($stmt = $this->_db->prepare($sql)){
                        $stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
                        $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                        $stmt->bindParam(":path", $path, PDO::PARAM_STR);
                        $stmt->execute();
                        $stmt->closeCursor();
                    }
                    //var_dump($FILES);
                    $target_file = $target_dir .basename($FILES[$file]["name"]);
                    $uploadOk = 1;
                    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
                    // Check if image file is a actual image or fake image
                    //if(isset($_POST["submit"])) {
                            $check = getimagesize($FILES[$file]["tmp_name"]);
                            if($check !== false) {
                                    //echo "File is an image - " . $check["mime"] . ".";
                                    $uploadOk = 1;
                            } else {
                                    //echo "File is not an image.";
                                    $uploadOk = 0;
                            }
                    //}
                    // Check if file already exists
                    //if (file_exists(l)) {
                    //        echo "Sorry, file already exists.";
                     //       $uploadOk = 0;
                    //}
                    // Check file size
                    if ($FILES[$file]["size"] > 500000) {
                            //echo "Sorry, your file is too large.";
                            $uploadOk = 0;
                    }
                    // Allow certain file formats
                    if($imageFileType != "jpg"
                        && $imageFileType != "png" 
                        && $imageFileType != "jpeg"
                        && $imageFileType != "gif"
                        && $imageFileType != "JPG" 
                        && $imageFileType != "PNG" 
                        && $imageFileType != "JPEG"
                        && $imageFileType != "GIF") {
                            //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                            $uploadOk = 0;
                    }
                    // Check if $uploadOk is set to 0 by an error
                    if ($uploadOk == 0) {
                          //  echo "Sorry, your file was not uploaded.";
                    // if everything is ok, try to upload file
                    } else {
                            if (move_uploaded_file($FILES[$file]["tmp_name"], $path)) {
                                    //echo "The file ". basename( $FILES[$file]["name"]). " has been uploaded.";
                            } else {
                                   // echo "Sorry, there was an error uploading your file.";
                            }
                    }
            }
	}
	
	public function adddelaymessageattachment($campaign_id, $delay_message_id, $FILES){
		$files = array ('file1','file2','file3');
                foreach($files as $file){
                    if(!isset($FILES[$file]) || $FILES[$file]["name"] == "") continue;
                    
                    $target_dir = $_SERVER["DOCUMENT_ROOT"] . '/bytefact/images/';
                    $path = $target_dir . time() . "_" . $FILES[$file]["name"];
                    $sql = "INSERT INTO delay_message_attachment(campaign_id, delay_message_id, path)
                            VALUES(:campaign_id, :delay_message_id, :path)";
                    if($stmt = $this->_db->prepare($sql)){
                        $stmt->bindParam(":delay_message_id", $delay_message_id, PDO::PARAM_INT);
                        $stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
                        $stmt->bindParam(":path", $path, PDO::PARAM_STR);
                        $stmt->execute();
                        $stmt->closeCursor();
                    }
                    //var_dump($FILES);
                    $target_file = $target_dir .basename($FILES[$file]["name"]);
                    $uploadOk = 1;
                    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
                    // Check if image file is a actual image or fake image
                    //if(isset($_POST["submit"])) {
                            $check = getimagesize($FILES[$file]["tmp_name"]);
                            if($check !== false) {
                                    //echo "File is an image - " . $check["mime"] . ".";
                                    $uploadOk = 1;
                            } else {
                                    //echo "File is not an image.";
                                    $uploadOk = 0;
                            }
                    //}
                    // Check if file already exists
                    //if (file_exists(l)) {
                    //        echo "Sorry, file already exists.";
                     //       $uploadOk = 0;
                    //}
                    // Check file size
                    if ($FILES[$file]["size"] > 500000) {
                            //echo "Sorry, your file is too large.";
                            $uploadOk = 0;
                    }
                    // Allow certain file formats
                    if($imageFileType != "jpg"
                        && $imageFileType != "png" 
                        && $imageFileType != "jpeg"
                        && $imageFileType != "gif"
                        && $imageFileType != "JPG" 
                        && $imageFileType != "PNG" 
                        && $imageFileType != "JPEG"
                        && $imageFileType != "GIF") {
                            //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                            $uploadOk = 0;
                    }
                    // Check if $uploadOk is set to 0 by an error
                    if ($uploadOk == 0) {
                          //  echo "Sorry, your file was not uploaded.";
                    // if everything is ok, try to upload file
                    } else {
                            if (move_uploaded_file($FILES[$file]["tmp_name"], $path)) {
                                    //echo "The file ". basename( $FILES[$file]["name"]). " has been uploaded.";
                            } else {
                                   // echo "Sorry, there was an error uploading your file.";
                            }
                    }
            }
}
	public static function makeClickableLinks($s) {
        return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1">my profile</a> ', $s);
    }
    
    function stri_replace( $find, $replace, $string ) {
        //Case-insensitive str_replace()
        $parts = explode( strtolower($find), strtolower($string) );
        $pos = 0;
        foreach( $parts as $key=>$part ){
            $parts[ $key ] = substr($string, $pos, strlen($part));
            $pos += strlen($part) + strlen($find);
        }

        return( join( $replace, $parts ) );
    }

    function txt2html($txt) {
        // Transforms txt in html

        //Kills double spaces and spaces inside tags.
        while( !( strpos($txt,'  ') === FALSE ) ) $txt = str_replace('  ',' ',$txt);
        $txt = str_replace(' >','>',$txt);
        $txt = str_replace('< ','<',$txt);

        //Transforms accents in html entities.
        //$txt = htmlentities($txt);

        //We need some HTML entities back!
        $txt = str_replace('"','"',$txt);
        $txt = str_replace('<','<',$txt);
        $txt = str_replace('>','>',$txt);
        $txt = str_replace('&','&',$txt);

        //Ajdusts links - anything starting with HTTP opens in a new window
        //$txt = $this->stri_replace("<a href=\"http://","<a target=\"_blank\" href=\"http://",$txt);
        //$txt = $this->stri_replace("<a href=http://","<a target=\"_blank\" href=http://",$txt);

        //Basic formatting
        $eol = ( strpos($txt,"\r") === FALSE ) ? "\n" : "\r\n";
        $html = '<p>'.str_replace("$eol$eol","</p><p>",$txt).'</p>';
        $html = str_replace("$eol","\n",$html);
        $html = str_replace("</p>","</p>\n\n",$html);
        $html = str_replace("<p></p>","<p> </p>",$html);

        //Wipes  after block tags (for when the user includes some html in the text).
        $wipebr = Array("table","tr","td","blockquote","ul","ol","li");

        for($x = 0; $x < count($wipebr); $x++) {

            $tag = $wipebr[$x];
            $html = $this->stri_replace("<$tag>
        ","<$tag>",$html);
            $html = $this->stri_replace("</$tag>
        ","</$tag>",$html);

        }

        return $html;
    }

	public function addmessage()
    {
		$campaign_id = trim($_GET['campaign']);
		$ishtml = trim($_POST['ishtml']);
		$delay = trim($_POST['delay']);
        $message = trim($_POST['message']);
		$message_id = $this->totalMessage($campaign_id) + 1;
		
		$message = $this->makeClickableLinks($message);
		//$message = nl2br($message);
		//$message = $this->txt2html($message);
		
		$FILES = $_FILES;	
		
		if(!$this->security->isNumeric($campaign_id)
			|| !$this->security->isNumeric($message_id)
			|| !$this->security->isNumeric($delay)
		){
			echo "<label> <font color=\"red\">Invalid Data, check your input.</font></label>";
			return;	
		}
		
				$sql = "INSERT INTO message(message_id, campaign_id, message, isHTML, delay)
                VALUES(:message_id, :campaign_id, :message, :ishtml, :delay)";
				
				
				if($stmt = $this->_db->prepare($sql))
				{
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
            		$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
					$stmt->bindParam(":message", $message, PDO::PARAM_STR);
					$stmt->bindParam(":ishtml", $ishtml, PDO::PARAM_INT);
					$stmt->bindParam(":delay", $delay, PDO::PARAM_INT);
        		    $stmt->execute();
		     		$stmt->closeCursor();
					
           			$messageID = $this->_db->lastInsertId();
            		$succeed = dechex($messageID);
					if(isset($succeed)){
            			echo "<label> <font color=\"green\"> Success! New MESSAGE is added.</font></label>";
					}
					else{
						echo "<label> <font color=\"red\">Failed! MESSAGE not added.</font></label>";
					}
        		} else {
            		echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        		}
				
				$this->addmessageattachment($campaign_id,$message_id,$FILES);
    }
	
	public function getAttachmentList($campaign_id, $message_id){
		$sql = "SELECT path from message_attachment WHERE campaign_id=:campaign_id AND message_id=:message_id";
		if($stmt = $this->_db->prepare($sql))
		{
        	$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
        	$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
			if($stmt->rowCount()!=0) 
			{
				$attachments = "";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
    				$row = $stmt->fetch();
					$from_arr = explode('/',chop($row['path']));
                    //$attachments = $attachments . $from_arr[count($from_arr)-1] . "<br/>";
                    $attachments = $attachments . "<img src=\"../images/{$from_arr[count($from_arr)-1]}\" alt=\"{$from_arr[count($from_arr)-1]}\" width=\"80\"><br/>";
				}
				return $attachments;
            }
		    else return "";
        }
	}
	
	public function getDelayAttachmentList($campaign_id, $message_id){
		$sql = "SELECT path from delay_message_attachment WHERE campaign_id=:campaign_id AND delay_message_id=:message_id";
		if($stmt = $this->_db->prepare($sql))
		{
        	$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
        	$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
			if($stmt->rowCount()!=0) 
			{
				$attachments = "";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
    				$row = $stmt->fetch();
					$from_arr = explode('/',chop($row['path']));
					//$attachments = $attachments . $from_arr[count($from_arr)-1] . "<br/>";
					$attachments = $attachments . "<img src=\"../images/{$from_arr[count($from_arr)-1]}\" alt=\"{$from_arr[count($from_arr)-1]}\" width=\"80\"><br/>";
				}
				return $attachments;
            }
		    else return "";
        }
	}
	
	
	
	public function messagelist($campaign_id)
	{
        $sql = "SELECT *
                FROM message WHERE campaign_id = :campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">MESSAGE list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen;\">";
					echo "<th style=\"font-size: 10px; color:white\">ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">DELAY</th>";
					echo "<th style=\"font-size: 10px; color:white\">MESSAGE</th>";
					echo "<th style=\"font-size: 10px; color:white\">ATTACHMENTS</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<tr>";
    				$row = $stmt->fetch();
						echo "<td>"; 
							echo $row['message_id'];
						echo "</td>";
                		echo "<td>";
							echo $row['delay'];
						echo "</td>";
                		echo "<td style=\"text-align: left !important;\">";
							echo $this->txt2html($row['message']);
						echo "</td>";
						echo "<td>";
							echo $this->getAttachmentList($campaign_id, $row['message_id']);
						echo "</td>";
                		echo "<td>";
							echo "<a href=\"javascript:messageedit('addnewmessage.php?edit=1&campaign=".$row['campaign_id']."&message=".$row['message_id']."','messageedit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";    
                		echo "<td>";
							echo "<a href=\"javascript:messagedelete('addnewmessage.php?delete=0&campaign=".$row['campaign_id']."&message=".$row['message_id']."','messagedelete','640','480','center','front');\">
        DELETE</a>";
						echo "</td>";    


					//echo "<br\>";
					echo "</tr>";
					//echo "<tr>";
					//echo "<td>"; echo "</td>";
					//echo "<td>"; echo "Insert a new MESSAGE HERE."; echo "</td>";
					//echo "</tr>";
					
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	public function deletemessage(){
		$campaign_id = trim($_GET['campaign']);
		$delete = trim($_GET['delete']);
		$message_id = trim($_GET['message']);

				$sql = "DELETE FROM message
					WHERE message_id=:message_id AND campaign_id=:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "UPDATE message
					SET message_id=message_id-1 WHERE message_id>:message_id AND campaign_id=:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
	}
	
	public function deletedelaymessage(){
		$campaign_id = trim($_GET['campaign']);
		$delete = trim($_GET['delete']);
		$message_id = trim($_GET['message']);
		$delaymessage_id = trim($_GET['delaymessage']);

				$sql = "DELETE FROM delay_message
					WHERE message_id=:message_id AND campaign_id=:campaign_id AND delay_message_id=:delaymessage_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
            		$stmt->bindParam(":delaymessage_id", $delaymessage_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
				
				$sql = "UPDATE delay_message
					SET delay_message_id=delay_message_id-1 WHERE delay_message_id>:delaymessage_id AND message_id=:message_id AND campaign_id=:campaign_id
				"
				;
				if($stmt = $this->_db->prepare($sql))
				{
					$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            		$stmt->bindParam(":message_id", $message_id, PDO::PARAM_INT);
					$stmt->bindParam(":delaymessage_id", $delaymessage_id, PDO::PARAM_INT);
					$stmt->execute();
		     		$stmt->closeCursor();
				}
	}
	
	public function delaymessagelist($campaign_id)
	{
        $sql = "SELECT *
                FROM delay_message WHERE campaign_id = :campaign_id";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":campaign_id", $campaign_id, PDO::PARAM_INT);
            $stmt->execute();
            if($stmt->rowCount()==0) 
			{
                echo "<label> <font color=\"red\">FOLLOW UP MESSAGE list is empty. </font></label>";
            }
			else
			{
				echo "<table>";
				echo "<tr style=\"background-color:limegreen\">";
					echo "<th style=\"font-size: 10px; color:white\">ID</th>";
					echo "<th style=\"font-size: 10px; color:white\">DELAY</th>";
					echo "<th style=\"font-size: 10px; color:white\">FOLLOW UP MESSAGE</th>";
					echo "<th style=\"font-size: 10px; color:white\">ATTACHMENTS</th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
					echo "<th style=\"font-size: 10px; color:white\"></th>";
				echo "</tr>";
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
					echo "<tr>";
    				$row = $stmt->fetch();
						echo "<td>"; 
							echo $row['delay_message_id'];
						echo "</td>";
						
                		echo "<td>";
							echo $row['delay'];
						echo "</td>";
                		
						echo "<td style=\"text-align: left !important;\">";
							echo $this->txt2html($row['delay_message']);
						echo "</td>";
						echo "<td>";
							echo $this->getDelayAttachmentList($campaign_id, $row['delay_message_id']);
						echo "</td>";
						echo "<td>";
							echo "<a href=\"javascript:messageedit('addnewdelaymessage.php?edit=1&campaign=". $row['campaign_id'] . "&message=". $row['message_id'] . "&delaymessage=". $row['delay_message_id'] ."','messageedit','640','480','center','front');\">
        EDIT</a>";
						echo "</td>";    
                		echo "<td>";
							echo "<a href=\"javascript:messagedelete('addnewdelaymessage.php?delete=0&campaign=". $row['campaign_id'] . "&message=". $row['message_id'] . "&delaymessage=". $row['delay_message_id'] ."','messagedelete','640','480','center','front');\">
        DELETE</a>";
						echo "</td>";       
					echo "</tr>";
				}
				echo "</table>";
			}
		}
		else
		{
        	echo "<label><font color=\"red\">Error! Sorry, Error in SQL.</font></label>";
        }
		
	}
	
	
	
	
}
?>
